import json
from pyecharts.charts import Map
from pyecharts.options import *

# 读取数据文件
f = open("/Users/zhangguoqiang/PycharmProjects/pythonProject/地图数据/疫情.txt", "r", encoding="UTF-8")
data = f.read()

# 关闭文件
f.close()

# 取到各省数据
# 将字符串json转换为python的字典
data_dict = json.loads(data)

# 从字典中取出省份数据
province_data_list = data_dict["areaTree"][0]["children"]

# 组装每个省份和确诊人数为元素，并各个省的数据都封装到列表内
data_list = []  # 绘图需要用的数据列表
for province_data in province_data_list:
    province_name = province_data["name"]   # 身份名称
    province_confirm = province_data["total"]["confirm"]    # 确诊人数
    # data_list.append((province_name, province_confirm))

    # 处理省份不匹配问题
    if province_name == "新疆":
        province_name = "新疆维吾尔自治区"
    elif province_name == "广西":
        province_name = "广西壮族自治区"
    elif province_name == "宁夏":
        province_name = "宁夏回族自治区"
    elif province_name in ["内蒙古", "西藏"]:
        province_name = province_name + "自治区"
    elif province_name in ["北京","天津","重庆","上海"]:
        province_name = province_name + "市"
    elif province_name in ["香港","澳门"]:
        province_name = province_name + "特别行政区"
    else:
        province_name = province_name + "省"
    data_list.append((province_name, province_confirm))

# 创建地图对象
map = Map()

# 添加数据
map.add("各省份确诊人数", data_list, "china")

# 设置全局选项，定制分段视觉映射
map.set_global_opts(
    title_opts=TitleOpts(title="全国疫情地图"),
    visualmap_opts=VisualMapOpts(
        is_show=True,
        is_piecewise=True,
        pieces=[
            {"min": 1, "max": 99, "label": "1-99", "color": "#FF6A6A"},
            {"min": 100, "max": 999, "label": "100-999", "color": "#EE6363"},
            {"min": 1000, "max": 4999, "label": "1000-4999", "color": "#FF4500"},
            {"min": 5000, "max": 9999, "label": "5000-9999", "color": "#EE4000"},
            {"min": 10000, "max": 99999, "label": "10000-99999", "color": "#CD3700"},
            {"min": 100000, "label": "100000+", "color": "#8B2500"},
        ]
    )
)

# 绘制地图对象
map.render("全国疫情地图.html")